package com.chenfan.mcn.utils;

import com.chenfan.common.exception.BusinessException;
import com.chenfan.mcn.exception.McnErrorCode;
import org.apache.commons.collections4.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 校验工具类
 *
 * @author wulg
 * @date 2021-11-22
 **/
public final class ValidatorUtil {

    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> void validate(T object) {
        validate(object, Default.class);
    }

    public static <T> void validate(T object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        for (ConstraintViolation<Object> c : constraintViolations) {
            throw new BusinessException(McnErrorCode.PARAM_ERROR.code(), c.getMessage());
        }
    }

    public static <T> String getJointValidateResult(T object, String separator) {
        return getJointValidateResult(object, separator, Default.class);
    }

    public static <T> String getJointValidateResult(T object, String separator, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if(CollectionUtils.isEmpty(constraintViolations)) {
            return null;
        }
        return constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(separator));
    }
}
